package com.project.service.impl;

import com.project.entity.po.Menu;
import com.project.entity.po.Receipt;
import com.project.entity.po.ReceiptMenuRelation;
import com.project.entity.po.User;
import com.project.entity.qo.ReceiptMenuRelationQo;
import com.project.entity.qo.ReceiptQo;
import com.project.entity.qo.SelectReceiptListQo;
import com.project.exception.ServiceException;
import com.project.mapper.MenuMapper;
import com.project.mapper.ReceiptMapper;
import com.project.mapper.ReceiptMenuRelationMapper;
import com.project.mapper.UserMapper;
import com.project.result.ResponseResult;
import com.project.result.ResultCode;
import com.project.service.ReceiptService;
import com.project.utils.OrderUtils;
import com.project.utils.ShiroUtils;
import com.project.entity.vo.ReceiptVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author qjj
 * @create 2022/3/28 16:59
 */
@Service
public class ReceiptServiceImpl  implements ReceiptService {
    @Resource
    private ReceiptMapper receiptMapper;

    @Resource
    private MenuMapper menuMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private ReceiptMenuRelationMapper rmrMapper;


    @Resource
    private OrderUtils orderUtils;

    /**
     * 添加发票
     * @param receiptQo
     * @return
     */
    @Override
    public ResponseResult<List<ReceiptVo>> addReceipt(ReceiptQo receiptQo) {
        Receipt receipt = new Receipt();
        BeanUtils.copyProperties(receiptQo,receipt);
        //获取用户id
        User user = (User) ShiroUtils.getSessionAttribute("user");
        Long userId = user.getUserId();
        receipt.setUserId(userId);
        //生成订单号
        String orderNumber = orderUtils.getOrderNumber();
        receipt.setOrderNumber(orderNumber);
        //下单时间
        Date date = new Date();
        receipt.setOrderTime(date);
        //总价
        Map<Long, Integer> menuId = receiptQo.getMenuId();
        Set<Long> set = menuId.keySet();
        Iterator<Long> it = set.iterator();
        Double total = 0.00;
        while (it.hasNext()){
            ReceiptMenuRelation rmr = new ReceiptMenuRelation();
            //获取菜单id
            Long key = it.next();
            //根据菜单id获取信息
            Menu menu = menuMapper.selectPriceById(key);
            //获取单价
            Double price = menu.getPrice();
            //获取每个菜数量
            Integer value = menuId.get(key);
            //计算总价
            total += price*value;

            rmr.setMenuId(key);
            rmr.setReceiptId(orderNumber);
            rmr.setNums(value);
            Integer add = rmrMapper.insert(rmr);
            if (add==0){
                throw new ServiceException(ResultCode.PARAM_IS_DEFICIENCY);
            }
        }
        receipt.setTotal(total);
        //判断是否安排了桌号，没有的话给0，也就是根据实际情况分配
        if (ObjectUtils.isEmpty(receiptQo.getTableNumber())){
            receipt.setTableNumber(0);
        }
        //折扣
        Double discout = 0.00;
        if (user.getVip() == 0){
            receipt.setDiscount(1.00);
        }else {
            discout = userMapper.getDiscout(user.getUserId());
            receipt.setDiscount(discout);
        }
        //实际支付
        Double actuallyPaid = total * discout;
        receipt.setActuallyPaid(actuallyPaid);
        //致谢词
        receipt.setConclusion("欢迎"+user.getUsername()+"来到有家餐馆");
        Integer integer = receiptMapper.addReceipt(receipt);
        if (integer == 0){
            throw new ServiceException(ResultCode.BUSINESS_UNKNOW_ERROR);
        }
        List<ReceiptVo> receipts = receiptMapper.seleteReceipt(null,orderNumber);
        if (ObjectUtils.isEmpty(receipts)){
            throw new ServiceException(ResultCode.BUSINESS_UNKNOW_ERROR);
        }
        return ResponseResult.success(receipts);
    }

    /**
     * 查看用户所有订单——可根据订单编号，手机号，以及无数据查询
     * @return
     */
    @Override
    public ResponseResult<List<ReceiptVo>> selectReceiptList(SelectReceiptListQo user1){
        Long userId = null;
        List<ReceiptVo> receiptVos = null;
        if (ObjectUtils.isEmpty(user1.getPhone()) && ObjectUtils.isEmpty(user1.getOrderNumber())){
            //获取用户id
            User user = (User) ShiroUtils.getSessionAttribute("user");
            userId = user.getUserId();
            receiptVos = receiptMapper.seleteReceipt(userId, null);
        }else if (!ObjectUtils.isEmpty(user1.getPhone())&&ObjectUtils.isEmpty(user1.getOrderNumber())){
            userId = userMapper.getUserId(user1.getPhone());
            receiptVos = receiptMapper.seleteReceipt(userId, null);
        }else if (!ObjectUtils.isEmpty(user1.getOrderNumber())){
            receiptVos = receiptMapper.seleteReceipt(null, user1.getOrderNumber());
        }
        if (ObjectUtils.isEmpty(receiptVos)){
            throw new ServiceException(ResultCode.BUSINESS_UNKNOW_ERROR);
        }
        return ResponseResult.success(receiptVos);
    }

    /**
     * 加菜
     * @param receiptMenuRelationQo1
     * @return
     */
    @Override
    public ResponseResult<String> addMenu(List<ReceiptMenuRelationQo> receiptMenuRelationQo1) {
        //获取中间对象
        ReceiptMenuRelation rmr = new ReceiptMenuRelation();
        //创建发票对象
        Receipt receipt = new Receipt();
        //遍历前段传过来的数据
        for (ReceiptMenuRelationQo receiptMenuRelationQo : receiptMenuRelationQo1) {
            //qo转po
            BeanUtils.copyProperties(receiptMenuRelationQo,rmr);
            BeanUtils.copyProperties(receiptMenuRelationQo,receipt);
            //加菜，错误则抛出错误
            int insert = rmrMapper.insert(rmr);
            if (insert == 0){
                throw new ServiceException(ResultCode.BUSINESS_UNKNOW_ERROR);
            }
            //获取菜的单价计算出这一次加菜
            Menu menu = menuMapper.selectPriceById(receiptMenuRelationQo.getMenuId());
            Double total1 = menu.getPrice()*receiptMenuRelationQo.getNums();
            //根据订单获取折扣和已有的总价
            List<ReceiptVo> receipts = receiptMapper.seleteReceipt(null,receiptMenuRelationQo.getReceiptId());
            Double discount = null;
            Double total = null;
            for (ReceiptVo receiptVo : receipts) {
                discount = receiptVo.getDiscount();
                total = receiptVo.getTotal();
            }
            //把单价加入到总价中，并给receipt中的总价赋值
            total += total1;
            receipt.setTotal(total);
            //根据总价和折扣获取最终实付的价格
            Double actuallyPaid = total*discount;
            receipt.setActuallyPaid(actuallyPaid);
            //给receipt对象的订单编号赋值
            receipt.setOrderNumber(receiptMenuRelationQo.getReceiptId());
            //调用updateReceipt方法修改发票信息
            Integer integer = receiptMapper.updateReceipt(receipt);
            if (integer == 0){
                throw new ServiceException(ResultCode.BUSINESS_UNKNOW_ERROR);
            }
        }
        return ResponseResult.success("添加成功");
    }

    /**
     * 删菜
     * @param rdrId1
     * @return
     */
    @Override
    public ResponseResult<String> deleteRmr(List<Long> rdrId1) {
        for (Long rdrId : rdrId1) {
            ReceiptMenuRelation rmr = rmrMapper.selectById(rdrId);
            if (ObjectUtils.isEmpty(rmr)){
                throw new ServiceException(ResultCode.BUSINESS_UNKNOW_ERROR);
            }
            int i = rmrMapper.deleteById(rdrId);
            if (i == 0){
                throw new ServiceException(ResultCode.BUSINESS_UNKNOW_ERROR);
            }
            //获取中间表对象的信息
            Receipt receipt = new Receipt();
            //根据单价获取当前总价格
            Menu menu = menuMapper.selectPriceById(rmr.getMenuId());
            Double num = menu.getPrice()*rmr.getNums();

            //根据订单获取折扣和已有的总价
            List<ReceiptVo> receipts = receiptMapper.seleteReceipt(null,rmr.getReceiptId());
            Double discount = null;
            Double total = null;
            for (ReceiptVo receiptVo : receipts) {
                discount = receiptVo.getDiscount();
                total = receiptVo.getTotal();
            }
            total -= num;
            receipt.setTotal(total);
            receipt.setOrderNumber(rmr.getReceiptId());
            Double actuallyPaid = total*discount;
            receipt.setActuallyPaid(actuallyPaid);
            Integer integer = receiptMapper.updateReceipt(receipt);
            if (integer == 0){
                throw new ServiceException(ResultCode.BUSINESS_UNKNOW_ERROR);
            }
        }
        return ResponseResult.success("删除成功");
    }

    /**
     * 修改菜信息
     * @param receiptMenuRelationQo
     * @return
     */
    @Override
    public ResponseResult<String> updateMenu(List<ReceiptMenuRelationQo> receiptMenuRelationQo) {
        ReceiptMenuRelation receiptMenuRelation = new ReceiptMenuRelation();
        for (ReceiptMenuRelationQo menuRelationQo : receiptMenuRelationQo) {
            BeanUtils.copyProperties(menuRelationQo,receiptMenuRelation);
            ReceiptMenuRelation rmr = rmrMapper.selectById(menuRelationQo.getRdrId());
            if (ObjectUtils.isEmpty(rmr)){
                throw new ServiceException(ResultCode.BUSINESS_UNKNOW_ERROR);
            }
            int i = rmrMapper.updateById(receiptMenuRelation);
            if(ObjectUtils.isEmpty(i)){
                throw new ServiceException(ResultCode.BUSINESS_UNKNOW_ERROR);
            }
            //获取中间表对象的信息
            Receipt receipt = new Receipt();
            //根据单价获取当前总价格
            Menu menu = menuMapper.selectPriceById(rmr.getMenuId());

            //根据订单获取折扣和已有的总价
            List<ReceiptVo> receipts = receiptMapper.seleteReceipt(null,rmr.getReceiptId());
            Double discount = null;
            Double total = null;
            for (ReceiptVo receiptVo : receipts) {
                discount = receiptVo.getDiscount();
                total = receiptVo.getTotal();
            }
            if (menuRelationQo.getNums() >= rmr.getNums()){
                Double num =(menuRelationQo.getNums()- rmr.getNums())*menu.getPrice();
                total += num;
            }else {
                Double num =(rmr.getNums()-menuRelationQo.getNums())*menu.getPrice();
                total -= num;
            }
            receipt.setTotal(total);
            receipt.setOrderNumber(rmr.getReceiptId());
            Double actuallyPaid = total*discount;
            receipt.setActuallyPaid(actuallyPaid);
            Integer integer = receiptMapper.updateReceipt(receipt);
            if (integer == 0){
                throw new ServiceException(ResultCode.BUSINESS_UNKNOW_ERROR);
            }
        }
        return ResponseResult.success("修改成功");
    }
}
